package com.star.niuke;

/**
 * @author: liminghui
 * @date: 2021/7/23 9:42
 * @version: 1.0
 * @description: 判断链表是否有环
 */
public class JudgeCycle {
    public boolean hasCycle(ListNode head) {
        if (head == null)
            return false;
        //快慢两个指针
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            //慢指针每次走一步
            slow = slow.next;
            //快指针每次走两步
            fast = fast.next.next;
            //如果相遇，说明有环，直接返回true
            if (slow == fast) {
                return true;
            }
        }
        //否则就是没环
        return false;

    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
